import router from './index.ts'
import pinia from '../store'
// 在组件外不能直接引入小仓库，需要先引入pinia大仓库
import useUserStore from '@/store/modules/user'
import nprogress from 'nprogress'
import setting from '@/setting.ts'
import 'nprogress/nprogress.css'

// 路由鉴权
router.beforeEach(async (to, from, next) => {
  // 路由切换时的进度条
  nprogress.start()
  const userStore = useUserStore(pinia)
  const token = userStore.token
  if (token) {
    // 已登录，不能跳转到登录界面
    if (to.path == '/login') {
      // 登录成功，访问login，不能访问，指向当前页面
      next({ path: from.path })
    } else {
      if (userStore.username) {
        next()
      } else {
        try {
          // 获取用户信息
          await userStore.userInfo()
          next()
        } catch {
          // token失效
          await userStore.logout()
          next({ path: '/login' })
        }
      }
    }
  } else {
    // 未登录，只能跳转到登录界面
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login' })
    }
  }
})

router.afterEach((to) => {
  document.title = `${setting.title}-${to.meta.title}`
  nprogress.done()
})
